<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Goods;
use plugin\admin\app\model\GoodsActivity;
use plugin\admin\app\model\GoodsActivityRelation;

class GoodsActivityService
{
    public static function goodsList(int $activityId, int $page = 1, int $length = 10, $order = ['id', 'desc'], $keyword = '')
    {
        $activity = GoodsActivity::where('id', $activityId)->first();

        if (!$activity) {
            throw new \Exception('不存在的活动');
        }

        if (!$activity['is_enable']) {
            throw new \Exception('该活动未启用');
        }

        if ($activity['start_time'] >= time() || $activity['end_time'] <= time()) {
            return Page::wrap(0, $page, $length, []);
        }

        $goodsIds = self::getActivityGoodsIds($activity);

        return GoodsService::list($page, $length, $order, 0, $keyword, $goodsIds, true);
    }

    public static function valid()
    {
        $activity = GoodsActivity::select(['id', 'name', 'type', 'discount', 'full', 'reduce', 'is_all_goods'])->where('is_enable', 1)->where('start_time', '<=', time())->where('end_time', '>=', time())->first();

        if (!$activity) {
            return null;
        }

        $activity['type_text'] = GoodsActivity::getTypeText($activity['type']);

        return $activity;
    }

    public static function getActivityGoodsIds($activity)
    {
        if ($activity && !$activity['is_all_goods']) {
            $relations = GoodsActivityRelation::where('activity_id', $activity['id'])->get()->toArray();
            $goodsIds = array_column($relations, 'goods_id');

            return $goodsIds;
        }

        return [];
    }

    public static function getGoodsJoinActivity($goodsInfo, $activity = null)
    {
        $activity = $activity ?? self::valid();
        $goodsIds = self::getActivityGoodsIds($activity);

        if ($activity) {
            if ($activity['is_all_goods']) {
                return $activity;
            } else {
                if (count($goodsIds) > 0 && in_array($goodsInfo['id'], $goodsIds)) {
                    return $activity;
                }
            }
        }

        return [];

    }

    public static function getActivityPrice(array $goodsIds)
    {
        $goodsList = Goods::whereIn('id', $goodsIds)->get()->toArray();

//        $relations = GoodsActivityRelation::whereIn('goods_id', $goodsIds)->first();
//
//        if ($relations) {
//            $activity = GoodsActivity::select(['name', 'type', 'discount'])->where('start_time', '<=', time())->where('end_time', '>=', time())->where('is_enable', 1)->where('id', $relation['activity_id'])->first();
//
//            if ($activity) {
//                $goodsInfo['activity'] = $activity;
//            }
//        }
    }
}